const { Sequelize } = require('sequelize');

const db = require("../initDB")

const RangModel = require("../models/ranking")
const UserModel = require("../models/users")
const rangModel = RangModel(db)
const userModel = UserModel(db)
const jwt = require("../Jwt/jwt")

const getRankingList = async (req, res) => {
    try {
        rangModel.belongsTo(userModel, { foreignKey: 'userId' });
        let rankingList = await rangModel.findAll({
            include: [
                {
                    model: userModel,
                    attributes: [
                        'id',
                        'createdAt',
                        'updatedAt',
                        'deletedAt',
                        'name',
                        'mobile',
                    ]
                }
            ],
            nest: true,
            order: [
                ['score', 'ASC']
            ],
            // attributes: ['id', 'createdAt', 'updatedAt', 'deletedAt', 'userId', 'ranking', 'score'],
            // dialectOptions: {
            //     flags: {
            //         sql_mode: 'only_full_group_by'
            //     }
            // },
            attributes: ['userId', [Sequelize.literal('MAX(score)'), 'score']],
            // attributes: { include: Sequelize.literal('MAX(score)')},
            group: ['userId'],
            raw: true,
            limit:10
        })

        res.SendSuccess(res, rankingList)
    } catch (err) {

        res.otherError(res, err.toString())

    }
}
const uploadScore = async (req, res) => {
    let bodyParams = req.body;
    let userId = jwt.getUserId(req);
    try {
        rangModel.create({
            "score": bodyParams.score,
            "ranking": '-',
            "userId": userId
        }).then((ranking) => {
            res.SendSuccess(res)
        }).catch((error) => {
            console.error('Error creating user:', error.message);
            res.otherError(res, error.toString())
        });
    } catch (err) {

        res.otherError(res, err.toString())

    }
}

const histroyScore = async (req, res) => {
    let userId = jwt.getUserId(req);

    let { limit, page } = req.query;
    let offset = (page - 1) * limit
    console.log("limit", limit)
    let histotyList = await rangModel.findAll({
        where: {
            userId
        },
        limit: Number(limit),
        offset,
    })
    res.SendSuccess(res, histotyList);
}


module.exports = {
    getRankingList,
    uploadScore,
    histroyScore
};